'use strict';
/**
 * Created by QianQi on 2017/2/10.
 */
var gulp=require('gulp');
var common = require('../common.js'),
    plugin = common.plugin,// package.json 中定义的插件
    config = common.config;// 配置
var pluginModify = require('./modify.js');// 依赖于自定义的 modify
module.exports = function(opts){
    var fGetPageStr=function(oConf){
        var str='',
            aDemo=oConf['demo'],
            aAttr=oConf['attr'],
            aPar=oConf['param'],
            aRet=oConf['return'];
        str+='<div class="wrap-head">' +
            '    <div class="wrap-head-r">'+oConf['type']+'</div>' +
            '    <div class="wrap-head-l">'+oConf['widoc']+'</div>' +
            '</div>' +
            '<div class="wrap-cont">' +
            '    <div class="wrap-cont-c">' +
            '        <div class="container">';
        str+='    <div class="panel">' +
            '        <div class="panel-h">描述</div>' +
            '        <div class="panel-c">' +
            '            <p class="des">'+oConf['des'].replace(/[\r\n]+/g,'<br/>')+'</p>' +
            '        </div>' +
            '    </div>';
        if(oConf['depends']){
            str+='    <div class="panel">' +
                '        <div class="panel-h">依赖</div>' +
                '        <div class="panel-c">' +
                '            <p class="des">'+oConf['depends'].replace(/[\r\n]+/g,'<br/>')+'</p>' +
                '        </div>' +
                '    </div>';
        }
        var nRow,nLen,oCur;
        if(aDemo.length){
            str+='<div class="panel blank-t">' +// blank-t 上方留白
                '<div class="panel-h">demo</div>' +// attr
                '<div class="panel-c">';
            str+='<table class="listtable"><tbody>';
            for(nRow=0,nLen=aDemo.length;nRow<nLen;nRow++){
                oCur=aDemo[nRow];
                str+='<tr>' +
                    '<td><div class="listtable-item"><a href="'+opts.dempPrev+oCur['lnk']+'.html">'+oCur['des'].replace(/[\r\n]+/g,'<br/>')+'</a></div></td>' +
                    '</tr>';
            }
            str+='</tbody></table>';
            str+='</div></div>';
        }
        if(aAttr.length){
            str+='<div class="panel blank-t">' +// blank-t 上方留白
                '<div class="panel-h">属性</div>' +// attr
                '<div class="panel-c">';
            str+='<table class="listtable"><thead><tr>' +
                '<th style="width:200px">名称</th>' +
                '<th style="width:100px">类型</th>' +
                '<th>描述</th>' +
                '</tr></thead><tbody>';
            for(nRow=0,nLen=aAttr.length;nRow<nLen;nRow++){
                oCur=aAttr[nRow];
                str+='<tr>' +
                    '<td><div class="listtable-item">'+oCur['name']+'</div></td>' +
                    '<td class="center"><div class="listtable-item">'+oCur['type'].replace(/\|/g,'<br/>')+'</div></td>' +
                    '<td><div class="listtable-item">'+oCur['des'].replace(/[\r\n]+/g,'<br/>')+'</div></td>' +
                    '</tr>';
            }
            str+='</tbody></table>';
            str+='</div></div>';
        }
        if(aPar.length){
            str+='<div class="panel blank-t">' +// blank-t 上方留白
                '<div class="panel-h">初始化参数</div>' +// param
                '<div class="panel-c">';
            str+='<table class="listtable"><thead><tr>' +
                '<th style="width:200px">名称</th>' +
                '<th style="width:100px">类型</th>' +
                '<th>描述</th>' +
                '<th style="width:60px">必填</th>' +
                '</tr></thead><tbody>';
            for(nRow=0,nLen=aPar.length;nRow<nLen;nRow++){
                oCur=aPar[nRow];
                str+='<tr>' +
                    '<td><div class="listtable-item">'+oCur['name']+'</div></td>' +
                    '<td class="center"><div class="listtable-item">'+oCur['type'].replace(/\|/g,'<br/>')+'</div></td>' +
                    '<td><div class="listtable-item">'+oCur['des'].replace(/[\r\n]+/g,'<br/>')+'</div></td>' +
                    '<td class="center"><div class="listtable-item">'+(oCur['required']?'是':'')+'</div></td>' +
                    '</tr>';
            }
            str+='</tbody></table>';
            str+='</div></div>';
        }
        if(aRet.length){
            str+='<div class="panel blank-t">' +// blank-t 上方留白
                '<div class="panel-h">返回值</div>' +// return
                '<div class="panel-c">';
            str+='<table class="listtable"><thead><tr>' +
                '<th style="width:200px">名称</th>' +
                '<th style="width:100px">类型</th>' +
                '<th>描述</th>' +
                '</tr></thead><tbody>';
            for(nRow=0,nLen=aRet.length;nRow<nLen;nRow++){
                oCur=aRet[nRow];
                str+='<tr>' +
                    '<td><div class="listtable-item">'+oCur['name']+'</div></td>' +
                    '<td class="center"><div class="listtable-item">'+oCur['type'].replace(/\|/g,'<br/>')+'</div></td>' +
                    '<td><div class="listtable-item">'+oCur['des'].replace(/[\r\n]+/g,'<br/>')+'</div></td>' +
                    '</tr>';
            }
            str+='</tbody></table>';
            str+='</div></div>';
        }
        str+='</div>' +
            '</div></div>';
        return str;
    };
    var fReplaceHandler=function(oConf){
        return function(content){
            return content.replace(/@{3}PAGECONTENT@{3}/g,fGetPageStr(oConf));
        };
    };
    return plugin.through2.obj(function(file, encoding, callback){
        if (file.isNull()) {
            return callback(null, file);
        }
        if (file.isStream()){
            return callback(createError(file, 'Streaming not supported'));
        }
        var nApiCount= 0,// 记录组件数量，生成对应 api 页面后 -1
            oMenu={
                aux:[],// 扩展功能
                comp:[],// 组件，原型扩展
                prop:[]// 原型扩展
            };
        var fItemHandler=function(idx,src){
            var str='',aConf,
                sType,sVal,// 每行的类型，对应的值
                oConf={
                    demo:[],
                    param:[],
                    return:[],
                    attr:[]
                };
            src=src.replace(/(^\/\*[\s\*]*@)|([\s\*]*\*\/$)/g,'');// 去除首位无内容的行
            aConf=src.split(/[\n\r]+[\s\*]*@/);// 根据换行后的 @ 标识分隔内容
            for(var i= 0,cur,len=aConf.length;i<len;i++){
                cur=aConf[i];
                sType='';
                sVal='';
                sVal=cur.replace(/^(\S+)\b\s+|\s*$/,function(){
                    sType=arguments[1];
                    return '';
                });
                if(sType && sVal){
                    if(sType=='param'||sType=='attr'||sType=='return'||sType=='rtn'){
                        sVal.replace(/^\{(.+?)}(?:\s+(\S+))?(?:\s+(\S[\s\S]*))?$/,(function(sType){
                            return function(){
                                var type = arguments[1].replace(/\s/g, ''),
                                    obj={
                                        name: arguments[2]||'',
                                        des: arguments[3]||''
                                    };
                                if(sType=='param'){
                                    obj['type']=type.replace('=', '');
                                    obj['required']=type.indexOf('=') == -1;// 是否必填
                                }else{
                                    obj['type']=type;
                                }
                                if(sType == 'return'){
                                    obj.type = '<span class="t_green">' + obj.type + '</span>';
                                }
                                if(sType == 'rtn'){
                                    sType = 'return';
                                }
                                oConf[sType].push(obj);
                            }
                        })(sType));
                    }
                    else if(sType=='demo'){
                        sVal.replace(/^(.+?)(?:\s+(\S[\s\S]*))?$/,(function(sType){
                            return function(){
                                var type = arguments[1].replace(/\s/g, ''),
                                    obj={
                                        lnk: type,
                                        des: arguments[2]||''
                                    };
                                oConf[sType].push(obj);
                            }
                        })(sType));
                    }
                    else{// widoc,des,depends,type,namespace
                        if(!oConf[sType]){
                            oConf[sType] = sVal.replace(/(?:^\s+)|(?:\s+$)/g, '');// 去除首尾空格
                        }
                    }
                }
            }
            oMenu[oConf['namespace']||'aux'].push({
                appcode: idx,
                appname: oConf['widoc'],
                accessaddress: idx+'.html'
            });
            gulp.src(opts.apiTemp)
                .pipe(pluginModify(fReplaceHandler(oConf)))
                .pipe(plugin.rename(idx+'.html'))
                .pipe(gulp.dest(opts.apiDest))
                .on( 'end', function(){
                    nApiCount--;
                    var content;
                    if(nApiCount==0){
                        content='var DATA='+
                            JSON.stringify({
                                // 侧边菜单
                                applications: {
                                    amsAppList:[
                                        {
                                            code: 'comp',
                                            appname: '组件',
                                            ico_class: 'fa-briefcase',// TODO 图标样式 -- http://www.thinkcmf.com/font/icons 里找
                                            amsAppList: oMenu['comp']
                                        },
                                        {
                                            code: 'aux',
                                            appname: '辅助功能',
                                            ico_class: 'fa-briefcase',
                                            amsAppList: oMenu['aux']
                                        },
                                        {
                                            code: 'pro',
                                            appname: '原型扩展',
                                            ico_class: 'fa-briefcase',
                                            amsAppList: oMenu['prop']
                                        }
                                    ]
                                }
                            })+
                            ';';
                        file.contents = Buffer.from(content);// 生成菜单内容
                        callback(null, file);
                    }
                });
            return str;
        };
        plugin.glob(file.path,function(err,files){
            if(err){
                callback(err);
            }
            else{
                var content = file.contents.toString();// 读取源代码
                var aMatches = content.match(/\/\*[\s\*]*@widoc\b[\s\S]*?\*\//g);// * 后加 ?，尽可能少的匹配
                nApiCount=aMatches.length;
                for(var i= 0,len=nApiCount;i<len;i++){
                    fItemHandler(i,aMatches[i]);
                }
            }
        });
    });
};